import axios from "axios";
import { produce } from "immer";
import { useState, useEffect } from "react";
import Pop from "./Pop";
export default function CRUD() {
  let [list, setList] = useState([]);
  let [popTitle, setPopTitle] = useState("");
  let [showPop, setShowPop] = useState(false);
  let [formData, setFormData] = useState({
    id: undefined,
    name: "",
    email: "",
    phone: "",
  });

  useEffect(() => {
    setTimeout(() => {
      let data = [
        {
          id: 1,
          name: "张三",
          email: "zhangsan@example.com",
          phone: "123456789",
        },
        {
          id: 2,
          name: "李四",
          email: "lisi@example.com",
          phone: "987654321",
        },
      ];
      setList(data);
    });
  }, []);

  useEffect(() => {
    console.log("更新");
    return () => {
      console.log("销毁");
    };
  }, [list]);

  const bindName = (e) => {
    setFormData(
      produce((draft) => {
        draft.name = e.target.value;
      })
    );
  };
  const bindEmail = (e) => {
    setFormData(
      produce((draft) => {
        draft.email = e.target.value;
      })
    );
  };
  const bindPhone = (e) => {
    setFormData(
      produce((draft) => {
        draft.phone = e.target.value;
      })
    );
  };
  const closePop = () => {
    setShowPop(false);
  };
  const showPopFn = () => {
    setShowPop(true);
  };
  const add = () => {
    setPopTitle("新增");
    setFormData({
      id: undefined,
      name: "",
      email: "",
      phone: "",
    });
    showPopFn();
  };
  const submit = () => {
    let { email, phone } = formData;

    //验证邮箱格式
    if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email)) {
      alert("邮箱格式不正确");
      return;
    }
    if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(phone)) {
      alert("手机格式不正确");
      return;
    }
    if (!this.state.formData.id) {
      console.log("新增");
      setList(
        produce((draft) => {
          draft.push({
            ...formData,
          });
        })
      );

      closePop();
    } else {
      console.log("编辑");

      setList(
        produce((draft) => {
          const index = draft.findIndex((item) => item.id === formData.id);
          if (index !== -1) {
            draft[index] = formData;
          }
        })
      );
      closePop();
    }
  };
  const deleteFn = (id) => {
    setList(
      produce((draft) => {
        let index = draft.findIndex((item) => item.id === id);
        draft.splice(index, 1);
      })
    );
  };
  const edit = (item) => {
    setFormData(item);
    setPopTitle("编辑");
    showPopFn();
  };
  return (
    // 相当于template 不渲染标签
    <>
      <div>
        <div className="search">
          <div>search</div>
        </div>

        <div onClick={add}>add</div>
      </div>
      {/* table渲染 */}
      <table cellSpacing={0} cellPadding={0}>
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {list.map((item) => {
            return (
              <tr key={item.name}>
                <td>{item.id}</td>
                <td>{item.name}</td>
                <td>{item.email}</td>
                <td>{item.phone}</td>
                <td>
                  <button onClick={() => edit(item)}>Edit</button>
                  <button onClick={() => deleteFn(item.id)}>Delete</button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <Pop
        title={popTitle}
        visible={showPop}
        onCancel={closePop}
        onConfirm={submit}
      >
        <form>
          <div>
            <label htmlFor="name">Name:</label>
            <input
              type="text"
              value={formData.name}
              onInput={bindName}
              name="name"
            />
          </div>
          <div>
            <label htmlFor="email">email:</label>
            <input
              type="text"
              value={formData.email}
              onInput={bindEmail}
              name="email"
            />
          </div>
          <div>
            <label htmlFor="phone">phone:</label>
            <input
              type="text"
              value={formData.phone}
              name="phone"
              onChange={bindPhone}
            />
          </div>
          <button onClick={submit}>submit</button>
        </form>
      </Pop>
    </>
  );
}
